package com.ljj.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class LogInterceptor {
    private static final Logger LOGGER = LoggerFactory.getLogger(LogInterceptor.class);
    String logStr= null;

    public Object around(ProceedingJoinPoint call){

        Object result;

        //取得类名和方法名
        String className = call.getTarget().getClass().getName();
        String methodName = call.getSignature().getName();

        //相当于前置通知
        logStr = className+"类的"+methodName+"方法开始执行******Start******";
        LOGGER.info(logStr);

        try{
            result = call.proceed();

            //相当于后置通知
            logStr = className + "." + methodName + "()方法正常执行结束...";
            LOGGER.info(logStr);

        } catch (Throwable throwable) {
            //相当于异常抛出后通知
            StackTraceElement stackTraceElement = throwable.getStackTrace()[throwable.getStackTrace().length - 1];

            Object[] args = call.getArgs();

            LOGGER.info("----------------------------------------------------------------------------------");
            LOGGER.info("===执行{}类的{}()方法的{}行",className,methodName,stackTraceElement.getLineNumber());
            LOGGER.info("===异常信息为：{}", throwable.fillInStackTrace().toString());
            LOGGER.info("===参数信息为：{}",args);

            return stackTraceElement;
        }finally {
            //相当于最终通知
            logStr = className + "类的" + methodName + "方法执行结束******End******";
            LOGGER.info(logStr);
        }
        return result;
    }
}
